#include<stdio.h> 
#include<stdlib.h>
#include<unistd.h> 
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>

#define NUM 128
#define CMD_NUM 64

int main()
{
  char command[NUM];
  for(;;)
  {
    //1.打印提示符
    printf("[yzy@myhostname mydir]# ");//要在同一行输入，不换行，所以不加\n 
    fflush(stdout);//刷新缓冲区，显示提示符

    //2.获取我们在命令行输入的字符串
    fgets(command,NUM,stdin);//从stdin最大读取NUM个字符进入command
    //输入敲得回车\n也会被读入进去，所以最后一位是\n
    //比如输入ls，实际是"ls\n\0"
    //为了防止\n被打印，所以我们要把\n换成\0
    command[strlen(command)-1] = '\0';

    //"ls -a -l -r\0";
    //3.解析命令行输入的字符串，char* argv[]
    char* argv[CMD_NUM] = {NULL};
    argv[0] = strtok(command," ");
    int i=1;
    while(argv[i] = strtok(NULL," "))
    {
      i++;
    }

    //4.检测命令是否需要shell本身执行，内建命令
    if(strcmp(argv[0],"cd") == 0){
      if(argv[1] != NULL)
        chdir(argv[1]);
        
      continue;
    }
    //5.执行第三方命令
    pid_t id = fork();
    if(id == 0){
      //child
      printf("i am child,pid:%d\n",getpid());
      execvp(argv[0],argv);
      exit(1);
    }
    waitpid(-1,NULL,0);
  }
}
